const hotMiddleware = require('webpack-hot-middleware')
const { PassThrough } = require('stream')

module.exports = (compiler, opts) => {
  const koaMiddleware = hotMiddleware(compiler, opts)

  return async function (ctx, next) {
    let stream = new PassThrough()
    ctx.body = stream
    await koaMiddleware(ctx.req, {
      end: (content) => {
        ctx.body = content
      },
      write: stream.write.bind(stream),
      writeHead: (status, headers) => {
        ctx.status = status
        ctx.set(headers)
      }
    }, next)
  }

  return middleware
}
